let empUrl = '/emp',
  global_page = 1,
  global_limit = 5,
  timeout = 300,
  topDistance = 30;

function isLogin() {
  $.get('/admin/isLogin', admin => {
    if (admin === '') {
      window.location.href = '/admin';
    } else {
      $('.layui-nav .name').html(admin.name);
    }
  });
}

function logout() {
  window.location.href = '/admin/logout';
}

function pageInfo() {
  isLogin();
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(add)', data => {
      let field = data.field;
      $.get(empUrl + '/findByName', {name: field.name}, emp => {
        if (emp !== '') {
          layer.msg('该员工信息已经录入');
        } else {
          if (!/1[3-9][0-9]{9}/ig.test(field.phone) && field.name.length !== 11) {
            layer.msg('手机号格式有误，请查证后再输入!');
          } else if (!/^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/ig.test(field.email)) {
            layer.msg('邮箱格式错误，请包涵\'@\'符以及邮箱地址!');
          } else {
            field['name'] = $('input[name=name]').val();
            $.post(empUrl + '/addEmp', field, result => {
              if (result > 0) {
                layer.msg('员工信息添加成功');
              } else {
                layer.msg('员工信息添加失败');
              }
              hideLayout($('#add-emp-layout'));
              loadEmp();
            });
          }
        }
      });
    });
    form.on('submit(edit)', data => {
      let field = data.field;
      $.post(empUrl + '/updateEmp', field, result => {
        if (result > 0) {
          layer.msg('员工' + field.name + '信息更新成功');
        } else {
          layer.msg('员工' + field.name + '信息更新失败');
        }
        hideLayout($('#edit-emp-layout'));
        loadEmp();
      });
    });
  });
}

pageInfo();

function loadEmp(name) {
  if (name === 'undefined') name = '';
  $.get(empUrl + '/findAll', {
    page: global_page,
    limit: global_limit,
    name: name
  }, empList => {
    if (empList.data.length === 0 && global_page > 1) {
      global_page--;
      loadEmp();
    }
    loadEmpList(empList);
    loadEmpPage(empList);
  });
}

function loadEmpList(info) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
      layer = layui.layer;
    table.render({
      elem: '#emp',
      data: info.data,
      toolbar: '#emp-toolbar',
      cols: [
        [
          {type: 'checkbox'},
          {field: 'name', title: '员工姓名'},
          {field: 'code', title: '员工编号', width: 300},
          {field: 'phone', title: '手机号'},
          {field: 'email', title: '邮箱'},
          {
            field: 'gender', title: '性别', templet: d => {
              return d.gender === 1 ? '男' : '女';
            }
          },
          {
            field: 'lock', title: '是否锁定', templet: d => {
              return d.lock === 1 ? '未锁定' : '已锁定';
            }
          },
          {title: '操作', toolbar: '#emp-tool'}
        ]
      ]
    });
    table.on('toolbar(emp)', obj => {
      let data = table.checkStatus(obj.config.id).data;
      switch (obj.event) {
        case 'add':
          showLayout($('#add-emp-layout'));
          break;
        case 'del':
          let ids = [];
          $.each(data, (i, v) => {
            ids[i] = v.id;
          });
          $.post(empUrl + '/delEmp/' + JSON.stringify(ids), result => {
            result = result > 0 ? '成功' : '失败';
            layer.msg('员工信息删除' + result + '!');
            loadEmp();
          });
          break;
      }
    });
    table.on('tool(emp)', obj => {
      let event = obj.event,
        data = obj.data;
      switch (event) {
        case 'detail':
          $.get(empUrl + '/findById/' + data.id, employee => {
            $('#emp-detail-layout .layout-title').html(employee.name + '的详细信息');
            let input = $('#emp-detail-layout').find('input'),
              lock = employee.lock === 1 ? '未锁定' : '已锁定',
              gender = employee.gender === 1 ? '男' : '女';
            $.each(input, i => {
              input.eq(i).val(employee[input.eq(i).attr('name')]);
            });
            $('input[name=lock]').val(lock);
            $('input[name=gender]').val(gender);
          });
          showLayout($('#emp-detail-layout'));
          break;
        case 'edit':
          $.get(empUrl + '/findById/' + data.id, employee => {
            $('#edit-emp-layout .layout-title').html(employee.name + '的详细信息');
            let input = $('#edit-emp-layout').find('input'),
              lock = employee.lock !== 1;
            $.each(input, i => {
              input.eq(i).val(employee[input.eq(i).attr('name')]);
            });
            $('#edit-emp-layout input[name=lock]').prop('checked', lock);
            for (let i = 0; i < 2; i++) {
              $('#edit-emp-layout input[type=radio]').eq(i).val(i);
            }
            $('#edit-emp-layout input[name=gender]').eq(employee.gender).attr('checked', 'checked');
            resetForm();
          });
          showLayout($('#edit-emp-layout'));
          break;
        case 'del':
          $.post(empUrl + '/delEmp/' + data.id, result => {
            result = result > 0 ? '成功' : '失败';
            layer.msg('员工信息删除' + result + '!');
            loadEmp();
          });
          break;
      }
    })
  })
}

function loadEmpPage(info) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'emp-page',
      curr: info.page,
      limit: info.limit,
      count: info.count,
      jump: function (obj, first) {
        if (!first) {
          global_page = obj.curr;
          loadEmp();
        }
      }
    });
  })
}

function search() {
  let name = $('#search').val();
  loadEmp(name);
}

function resetForm() {
  layui.use('form', () => {
    layui.form.render();
  })
}

/* --- 自定义弹出层动画 --- */

function loadLayoutSize() {
  let layoutBox = $('.layout-box');
  $.each(layoutBox, function (i) {
    layoutBox.eq(i).css('margin-top', '-' + (layoutBox.eq(i).height() / 2 + topDistance) + 'px');
  });
}

loadLayoutSize();

function showLayout(elem) {
  let layoutBox = elem.children('.layout-box');
  elem.children('.layout-background').removeClass('display-none').animate({
    'opacity': .5
  }, timeout);
  layoutBox.removeClass('display-none').animate({
    'margin-top': '-' + (layoutBox.height() / 2) + 'px',
    'opacity': 1
  }, timeout);
}

function hideLayout(elem) {
  let layoutBox = elem.children('.layout-box');
  elem.children('.layout-background').animate({
    'opacity': 0
  }, timeout);
  layoutBox.animate({
    'margin-top': '-' + (layoutBox.height() / 2 + topDistance) + 'px',
    'opacity': 0
  }, timeout);
  setTimeout(() => {
    elem.children('.layout-background, .layout-box').addClass('display-none');
    elem.find('input, textarea').val('');
  }, timeout);
}

/* --- --- */